package com.xiaolong.web.serializer;

import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.ObjectSerializer;
import com.alibaba.fastjson.serializer.SerializeWriter;
import com.alibaba.fastjson.util.TypeUtils;

import java.io.IOException;
import java.lang.reflect.Type;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Date;

public class DateSerializer implements ObjectSerializer {
    public static final DateSerializer INSTANCE = new DateSerializer();

    public DateSerializer() {
    }

    public static Class<?>[] getDateClassArray() {
        return new Class[]{Date.class, java.sql.Date.class, Time.class, Timestamp.class};
    }

    public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException {
        SerializeWriter out = serializer.out;
        if (object == null) {
            out.writeNull();
        } else {
            Date date;
            if (object instanceof Date) {
                date = (Date)object;
            } else {
                date = TypeUtils.castToDate(object);
            }

            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            StringBuilder builder = new StringBuilder(32);
            int year = calendar.get(1);
            int month = calendar.get(2) + 1;
            int day = calendar.get(5);
            int hour = calendar.get(11);
            int minute = calendar.get(12);
            int second = calendar.get(13);
            builder.append(year);
            builder.append("-");
            this.addValue(builder, month);
            builder.append("-");
            this.addValue(builder, day);
            if (hour != 0 || minute != 0 || second != 0) {
                builder.append(" ");
                this.addValue(builder, hour);
                builder.append(":");
                this.addValue(builder, minute);
                builder.append(":");
                this.addValue(builder, second);
            }

            out.writeString(builder.toString());
        }
    }

    private void addValue(StringBuilder builder, int value) {
        builder.append(value > 9 ? Integer.toString(value) : "0" + value);
    }
}
